package net.ys.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.ys.bean.SwAlarm;
import net.ys.config.SystemConfig;
import net.ys.utils.Tools;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author: NMY
 * @Date: 2021/7/7
 * @Time: 14:46
 */
@Service
public class ApiService {

    @Resource
    private SystemConfig systemConfig;

    public boolean dingTalk(HttpServletRequest request) throws Exception {
        String parameter = parseParameter(request);
        JSONObject msg = JSONObject.parseObject(parameter);
        long timestamp = System.currentTimeMillis();
        String sign = Tools.ddSign(timestamp, systemConfig.getDdSecret());
        String url = String.format(systemConfig.getDdUrl(), timestamp, sign);
        return Tools.ddNotice(url, msg);
    }

    public boolean wx(HttpServletRequest request) throws Exception {
        String parameter = parseParameter(request);
        JSONObject obj = JSONObject.parseObject(parameter);
        String content = obj.getJSONObject("markdown").getString("text").replace("#  ", "").replaceAll("\\n \\n", "\\\n");
        return Tools.wxNotice(systemConfig.getWxUrl(), content);
    }

    public boolean prom(HttpServletRequest request) throws IOException {

        String parameter = parseParameter(request);
        String key = request.getParameter("key");
        if (key == null || "".equals(key.trim())) {
            key = systemConfig.getWxKey();
        }

        JSONObject obj = JSONObject.parseObject(parameter);

        StringBuffer sb = new StringBuffer();
        JSONArray alerts = obj.getJSONArray("alerts");
        JSONObject tmp = alerts.getJSONObject(0);

        String startsAt = tmp.getString("startsAt");
        String endsAt = tmp.getString("endsAt");

        String status = tmp.getString("status");
        JSONObject annotations = tmp.getJSONObject("annotations");
        JSONObject labels = tmp.getJSONObject("labels");

        String alertName = labels.getString("alertname");
        String type = labels.getString("type");
        String level = labels.getString("severity");
        sb.append("<font size='30'>**").append("PROMETHEUS报警").append("**</font>\n");
        sb.append("监控指标：").append(alertName).append("\n")
                .append("服务状态：");

        if ("resolved".equals(status)) {
            sb.append("<font color='green'>");
        } else {
            sb.append("<font color='red'>");
        }
        sb.append(status).append("</font>\n");

        sb.append("告警等级：");

        if ("resolved".equals(status)) {
            sb.append("<font color='green'>");
        } else {
            if (level.equals("FATAL")) {
                sb.append("<font color='red'>");
            } else {
                sb.append("<font color='warning'>");
            }
        }

        sb.append(level).append("</font>\n");

        if (endsAt.startsWith("0001")) {
            sb.append("告警时间：").append(Tools.toYmdHms(System.currentTimeMillis()));
        } else {
            sb.append("恢复时间：").append(Tools.toYmdHms(System.currentTimeMillis()));
        }
        sb.append("\n");

        if ("public".equals(type)) {
            sb.append("告警服务：");
            for (int i = 0; i < alerts.size(); i++) {
                tmp = alerts.getJSONObject(i);
                labels = tmp.getJSONObject("labels");
                String instance = labels.getString("instance");
                if (!StringUtils.hasLength(instance)) {
                    instance = labels.getString("application");
                }
                sb.append("**").append(instance).append("**、");
            }
            sb.append("\n");
            String description = annotations.getString("description");
            sb.append("告警描述：").append(description).append("\n");
        } else {
            for (int i = 0; i < alerts.size(); i++) {
                sb.append("告警服务：");
                tmp = alerts.getJSONObject(i);
                labels = tmp.getJSONObject("labels");
                String instance = labels.getString("instance");
                if (!StringUtils.hasLength(instance)) {
                    instance = labels.getString("application");
                }
                sb.append("**").append(instance).append("**\n");
                String description = annotations.getString("description");
                sb.append("告警描述：").append(description).append("\n");
            }
        }

        return Tools.wxNotice(systemConfig.getWxUrl() + key, sb.toString());
    }

    public String parseParameter(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        int len;
        byte[] bytes = new byte[1024];
        StringBuffer sb = new StringBuffer();
        while ((len = inputStream.read(bytes)) > 0) {
            sb.append(new String(bytes, 0, len));
        }

        String result = sb.toString();
        System.out.println(result);
        return result;
    }

    public Object sky(List<SwAlarm> alarmList) {
        String content = getContent(alarmList);
        return Tools.wxNotice(systemConfig.getWxUrl(), content);
    }

    private String getContent(List<SwAlarm> alarmList) {
        StringBuilder sb = new StringBuilder();
        sb.append("<font size='30'>**").append("SKY-WALKING报警").append("**</font>\n");
        for (SwAlarm alarm : alarmList) {
            sb.append("服务名称: ").append("<font color='red'>**").append(alarm.getName()).append("**</font>\n")
                    .append("告警规则: ").append(alarm.getRuleName()).append("\n")
                    .append("告警内容: ").append(alarm.getAlarmMessage()).append("\n")
                    .append("告警时间: ").append(Tools.toYmdHms(alarm.getStartTime())).append("\n")
                    .append("---------------\n");
        }
        return sb.toString();
    }
}
